package com.zzwx.controller.sys;

import com.zzwx.controller.dto.MyDatePropertyEditor;
import com.zzwx.dao.dto.UserAndRoleDTO;
import com.zzwx.dao.entity.sys.Menu;
import com.zzwx.dao.entity.sys.User;
import com.zzwx.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        binder.registerCustomEditor(Date.class, new MyDatePropertyEditor("yyyy-MM-dd HH:mm:ss"));
    }

    @RequestMapping(value = "findUsers",method = RequestMethod.GET)
    public String findUsers(HttpServletRequest request,Model model){
        List<User> users = userService.findUsers();
        model.addAttribute("users",users);
        return "sys/users_list";
    }

    @RequestMapping(value = "findMenus",method = RequestMethod.GET)
    public String findMenus(HttpServletRequest request,Model model){
        Subject subject = SecurityUtils.getSubject();
        System.out.println("当前路径 ： " + request.getServletPath());
        boolean isPermitted = subject.isPermitted(request.getServletPath());
        if(isPermitted){
            List<Menu> menus = userService.findMenus();
            model.addAttribute("menus",menus);
            return "sys/menus_list";
        }else{
            return "403";
        }
    }

    @RequestMapping(value = "findMenus/{menuId}",method = RequestMethod.GET)
    @ResponseBody
    public Menu findMenuById(@PathVariable("menuId") int menuId){
        return userService.findMenuById(menuId);
    }

    @RequestMapping(value = "getUserAndRole",method = RequestMethod.GET)
    public String getUserAndRole(Model model){
        try {
            List<UserAndRoleDTO> data =  userService.getUserAndRoles();
            model.addAttribute("data",data);
            return "sys/userAndRole_list";
        }catch (Exception e){
            e.printStackTrace();
            return "500";
        }
    }
}
